package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class NIOServer {

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    public static final int PORT = 6666;

    public NIOServer() {

        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        System.out.println("当前线程id为" + Thread.currentThread().getId());
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                        if (selectionKey.isReadable()) {
                            readData(selectionKey);
                        }
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待状态");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void readData(SelectionKey selectionKey) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(byteBuffer);
            if (count > 0) {
                String msg = new String(byteBuffer.array());
                System.out.println("客户端的消息：" + msg);
                sendInfoToOtherClient(msg,socketChannel);
            }

        } catch (Exception e) {

            try {
                assert socketChannel != null;
                System.out.println(socketChannel.getRemoteAddress() + " 离线了..");
                //取消注册
                selectionKey.cancel();
                //关闭通道
                socketChannel.close();
            } catch (Exception e2) {
                e2.printStackTrace();
                ;
            }
        }
    }

    public void sendInfoToOtherClient(String info,SocketChannel socketChannel) throws IOException {
        System.out.println("服务器转发消息中...");
        System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
        for (SelectionKey key : selector.keys()) {
            Channel channel=key.channel();
            if(channel instanceof SocketChannel&&channel!=socketChannel){
                SocketChannel destChannel=(SocketChannel)channel;
                ByteBuffer byteBuffer=ByteBuffer.wrap(info.getBytes());
                destChannel.write(byteBuffer);

            }
        }

    }

    public static void main(String[] args) {
        NIOServer niOServer=new NIOServer();
        niOServer.listen();
    }
}
